package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.etoak.common.core.vo.PageVO;
import com.etoak.common.web.exception.CustomException;
import com.etoak.entity.Ingredients;
import com.etoak.mapper.IngredientsMapper;
import com.etoak.service.IngredientsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author et2403
 * @since 2024-08-13
 */
@Service
public class IngredientsServiceImpl extends ServiceImpl<IngredientsMapper, Ingredients> implements IngredientsService {

    @Override
    public void add(Ingredients ingredients) {
        Ingredients savedingredients = getByName(ingredients.getName());
        if (ObjectUtils.isNotEmpty(savedingredients)){
            throw new CustomException("食材名称重复！");
        }

        ingredients.setCreateTime(DateUtil.now());
        save(ingredients);
    }

    @Override
    public PageVO<Ingredients> getList(int pageNum, int pageSize, Ingredients ingredients) {
        PageHelper.startPage(pageNum,pageSize);
        List<Ingredients> ingredientsList = baseMapper.getList(ingredients);
        PageInfo<Ingredients> pageInfo = new PageInfo<>(ingredientsList);
        return new PageVO<>(pageInfo.getPageNum(),pageInfo.getPageSize(),pageInfo.getList(),pageInfo.getTotal());
    }

    @Override
    public void update(int id, Ingredients ingredients) {
        /*验证id*/
        if (ObjectUtils.isEmpty(this.getById(id))){
            throw new CustomException("食材不存在!");
        }

        /*验证名称是否重复*/
        String ingredientsName = ingredients.getName();
        if (StringUtils.isNotEmpty(ingredientsName)){
            Ingredients savedIngredients = this.getByName(ingredientsName);

            if (ObjectUtils.isNotEmpty(savedIngredients) && !savedIngredients.getId().equals(id)){
                throw new CustomException("食材名称重复啦！");
            }
        }

        /* 更新 */
        ingredients.setId(id);
        ingredients.setUpdateTime(DateUtil.now());
        updateById(ingredients);
    }

    @Override
    public void delete(int id) {
        /*判断 id*/
        if (ObjectUtils.isEmpty(getById(id))){
            throw new CustomException("食材不存在！");
        }

        //TODO 判断食材是否被菜品使用
        this.removeById(id);
    }

    private Ingredients getByName(String name) {
        return lambdaQuery().eq(Ingredients::getName,name).one();
    }
}
